<template>
  <n-modal
    title="分配角色"
    style="width: 50%"
    :mask-closable="false"
    :close-on-esc="false"
    preset="card"
    :show="show"
    @close="close"
    :on-after-enter="init"
    :on-after-leave="destroy"
  >
    <n-data-table
      table-layout="fixed"
      :bordered="false"
      :columns="columns"
      :data="records"
      :row-key="(row: BaseRolePO) => row.id"
      :default-checked-row-keys="checkedKeys"
      @update:checked-row-keys="handleCheck"
      remote
    />
    <template #footer>
      <n-space justify="end">
        <n-button @click="close">关闭</n-button>
        <n-button type="info" @click="handleConfirmOnClick">确认</n-button>
      </n-space>
    </template>
  </n-modal>
</template>
<script lang="ts" setup>
import { getRoleList } from '@/api/base/Role'
import { getUserRoleRelationList, postUserRoleRelation } from '@/api/base/UserRoleRelation'

const state = reactive({
  records: [] as BaseRolePO[],
  checkedKeys: [] as string[]
})

const { records, checkedKeys } = toRefs(state)

const props = defineProps({
  show: {
    type: Boolean,
    required: true
  },
  row: {
    type: Object as PropType<BaseUserPO>,
    required: true
  }
})

const emits = defineEmits<{
  (e: 'handleCloseOnClick'): void
  (e: 'handleSelectOnClick'): void
}>()

const columns: DataTableColumns<BaseRolePO> = [
  { type: 'selection' },
  { key: 'id', title: '主键' },
  { key: 'name', title: '名称' }
]

const handleCheck = (keys: Array<string | number>) => {
  state.checkedKeys = keys as string[]
}

const init = async () => {
  const { data: list } = await getRoleList()
  state.records = list

  const relation: BaseUserRoleRelationPO = { userId: props.row.id }
  const { data: checkedList } = await getUserRoleRelationList(relation)
  list
    .filter((role) => {
      return checkedList.map((ele) => ele.roleId).includes(role.id)
    })
    .forEach((role) => {
      state.checkedKeys.push(role.id)
    })
}

const handleConfirmOnClick = async () => {
  const params = {
    userId: props.row.id,
    roleIds: state.checkedKeys
  }
  await postUserRoleRelation(params)
  select()
  close()
}

const select = () => {
  emits('handleSelectOnClick')
}

const close = () => {
  emits('handleCloseOnClick')
}

const destroy = () => {
  state.checkedKeys = []
}
</script>
